<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
define('CONTROLLER', 'truyencuoi');

class Vovaad extends CI_Controller {

     function __construct() {
        parent::__construct();
        $this->load->library(array('parser', 'form_validation', 'pagination'));
        $this->load->model('Vova_model');
        $this->lang->load('vi', 'vietnamese');
        $this->load->helper(array('url', 'paging', 'form'));
    }

    public function index($query_id = 0) {
        $data['act_title'] = 'Danh sách';
        $uri_segment = 5;
        $per_page = 10;

        $this->input->load_query($query_id);
        $query_array = array(
            'search' => $this->input->get('search'),
            'check' => $this->input->get('check'),
        );
        //print_r($query_array); return;
        $data['query_array'] = $query_array;
        $data['query_id'] = $query_id;

        $search = '';
        $base_url = base_admin_url("vovaad/index/$query_id/");
        $total_rows =  $this->Vova_model->getCountVova($query_array);
        $data['total'] = $total_rows;

        $config = config_paging($total_rows, $base_url, $per_page, $uri_segment);
        $this->pagination->initialize($config);

        $data['list'] = array();
        $result = $this->Vova_model->getListVova($per_page, $this->uri->segment($uri_segment), $query_array);
        $data['list'] = $result;

        $this->_set_radio($data, $query_array['check']);
        $this->_view($data, 'admin/vova/listvova.php');
    }

    public function search() {
        if ($this->input->post('search') == '' && $this->input->post('check') == 0) {
            redirect("admin/vovaad/index/0");
        }

        $query_array = array(
            'search' => $this->input->post('search'),
            'check' => $this->input->post('check'),
        );
        $query_id = $this->input->save_query($query_array);
        redirect("admin/vovaad/index/$query_id");
    }

    public function insert() {
        $path_view = 'admin/vova/insert_vova.php';
        $data['act_title'] = 'Thêm mới';

        $this->_set_rules();
        if ($this->form_validation->run() == FALSE)
        {
            $this->_view($data, $path_view);
        } else {
            $result = $this->Vova_model->insert_vova();
            redirect('admin/vovaad/index');
        }
    }

    public function edit() {
        $path_view = 'admin/vova/edit_vova.php';
        $data['act_title'] = 'Sửa thông tin';

        // check id edit
        $id = $this->uri->segment(4);
        $vova = $this->Vova_model->getAdminVovaById($id);
        $data['vova'] = $vova;
        if (!empty($vova)) {
            $data['url_user'] = create_url(CONTROLLER, $vova['id'], $vova['title']);
        }

        $this->_set_rules();
        $this->form_validation->set_rules('id', 'ID', 'required');
        if ($this->form_validation->run() == FALSE)
        {
            $this->_view($data, $path_view);
        } else {
            $id = $this->input->post('id');
            $result = $this->Vova_model->update_vova($id);
            redirect('admin/vovaad/index');
        }
    }

    public function delete() {
        $id = $this->uri->segment(4);
        $result = $this->Vova_model->delete_vova($id);
        redirect('admin/vovaad/index');
    }

    public function tools() {
        $data = array();
        $data['act_title'] = 'Copy truyện từ web khác';
        $urlpost = $this->input->post('url');
        //'http://www.truyencuoihay.vn/truyen-tieu-lam?pagenumber=23';
        if (isset($urlpost) && $urlpost != '') {
            $ex = explode('=', $urlpost);
            $url = $ex[0];
            $page = $ex[1];

            $this->load->helper('html_dom');
            while ($page > 0) {
                $urlload = $url . '=' . $page;
                $html = file_get_html($urlload);
                $arrData = array();
                foreach($html->find('.product-title a') as $key => $element) {
                    $arrData[$key]['title'] = $this->br2nl($element->innertext);
                    $arrData[$key]['character'] = '';
                    $arrData[$key]['check'] = 0;
                }
                foreach($html->find('.description') as $key => $element) {
                    $arrData[$key]['content'] = $this->br2nl($element->innertext);
                }

                if (!empty($arrData) && is_array($arrData)) {
                    $result = $this->Vova_model->insert_tools_vova($arrData);
                }

                $page--;
            }
            $data['url_data'] = $url;
        }
        $this->_view($data, 'admin/vova/tools.php');
    }

    /**
     * Convert BR tags to nl
     *
     * @param string The string to convert
     * @return string The converted string
     */
    private function br2nl($string)
    {
        $string = mb_convert_encoding($string, 'HTML-ENTITIES', 'auto');
        $string = mb_convert_encoding($string, 'UTF-8', 'HTML-ENTITIES');
        $string = str_replace('&nbsp;', ' ', $string);
        $string = str_replace('-', '<br>-', $string);
        $string = trim(preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string));
        $string = strip_tags($string);

        return $string;
    }

    public function check() {
        $this->load->library('session');
        $data['act_title'] = 'Duyệt truyện';
        $id = $this->input->post('id');
        $arrId = array();

        if (!empty($id) && $id > 0) {
            $idS = $this->session->userdata('ids');
            if (!empty($idS)) {
                $arrId = $idS;
            }
            if ($this->input->post('btCancel')) {
                $arrId[] = $id;
                $this->session->set_userdata(array('ids' => $arrId));
            }
            if ($this->input->post('btOk')) {
                $this->Vova_model->update_check_vova($id, 1);
            }
            if ($this->input->post('btNo')) {
                $this->Vova_model->update_check_vova($id, 2);
            }
            if ($this->input->post('btEdit')) {
                redirect("admin/vovaad/edit/$id");
            }
        }

        $result = $this->Vova_model->getAdminVovaCheck($arrId);
        $data['vova'] = $result;

        $this->_view($data, 'admin/vova/check_vova.php');
    }

    public function checkedit() {
        $this->_set_rules();
        $this->form_validation->set_rules('id', 'ID', 'required');
        if ($this->form_validation->run() == FALSE)
        {
            $this->check();
        } else {
            $id = $this->input->post('id');
            $result = $this->Vova_model->update_vova($id);
            redirect('admin/vovaad/check');
        }
    }

    private function _set_rules() {
        $this->form_validation->set_message('required', $this->lang->line('required'));
        $this->form_validation->set_rules('title', 'Tiêu đề', 'required');
        $this->form_validation->set_rules('content', 'Nội dung', 'required');
    }

    private function _set_radio(&$data, $check = 0) {
        $checkDefault = array_fill(0, 4, 0);
        switch ($check) {
            case 0:
                $checkDefault[0] = TRUE;
            break;
            case 1:
                $checkDefault[1] = TRUE;
                break;
            case 2:
                $checkDefault[2] = TRUE;
                break;
            case 3:
                $checkDefault[3] = TRUE;
                break;
        }

        $data['check0'] = form_radio('check', '0', $checkDefault[0]);
        $data['check1'] = form_radio('check', '1', $checkDefault[1]);
        $data['check2'] = form_radio('check', '2', $checkDefault[2]);
        $data['check3'] = form_radio('check', '3', $checkDefault[3]);
    }

    private function _view($data, $path) {
        $data['head_product'] = ucfirst('App Facebook Truyện cười vova, Tử vi 2014');
        $data['head_title'] = ucfirst('Quản Lý Truyện cười Vova');

        $this->parser->parse($path, $data, FALSE);
    }
}

/* End of file vova.php */
/* Location: ./application/controllers/vova.php */